package com.liuwei.msmall.common.exception;

import com.liuwei.msmall.common.enums.ErrorCode;
import com.liuwei.msmall.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 统一进行异常处理
 * @author llww
 * @date 2021/2/25 14:46
 */
@RestControllerAdvice
public class CustomExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class);

    @ExceptionHandler({Exception.class})
    public R handleException(Exception exp){

        if (exp instanceof BindException){
            String defaultMessage = ((BindException) exp).getBindingResult().getAllErrors().get(0).getDefaultMessage();
            return R.error(defaultMessage);
        }

        if (exp instanceof BusinessException){
            log.error("business exception", exp);
            return R.error(((BusinessException) exp).getCode(),((BusinessException) exp).getUserMessage());
        }

        if (exp instanceof RRException){
            log.error("RRException :", exp);
            return R.error(((RRException) exp).getCode(),((RRException) exp).getMsg());
        }

        if (exp instanceof HttpRequestMethodNotSupportedException){
            return R.error(ErrorCode.METHOD_NOT_ALLOWED.getCode(),ErrorCode.METHOD_NOT_ALLOWED.getMsg());
        }

        if (exp instanceof NoHandlerFoundException){
            return R.error(ErrorCode.NOT_FOUND.getCode(),ErrorCode.NOT_FOUND.getMsg());
        }

        log.error("没有处理的Exception :", exp);
        return R.error(ErrorCode.SYSTEM_ERROR.getCode(),ErrorCode.SYSTEM_ERROR.getMsg());
    }


}
